package daoimpl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import model.ProductCartDetail;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import pojo.Carrier;
import pojo.Cart;
import pojo.CartDetail;
import pojo.Overview;
import pojo.ProductImage;
import pojo.Specification;
import dao.CartDAO;

@Repository("CartDAO")
public class CartDAOImpl implements CartDAO {

	private SessionFactory sessionFactory;
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public List<Cart> getAllCart() {
		List<Cart> ds = null;
		
		Session session = null;
		try{
			session = sessionFactory.getCurrentSession();
		}
		catch(HibernateException ex)
		{
			session = sessionFactory.openSession();
		}
			
        try {
            String hql = "Select c from Cart c";
            Query query = session.createQuery(hql);
            ds = query.list();
        } catch (HibernateException ex) {
            System.err.println(ex);
        } finally {
        	session.close();
        }
        return ds;
	}

	public Cart getCartByID(String id) {
		Cart c = null;
		
		Session session = null;
		try{
			session = sessionFactory.getCurrentSession();
		}
		catch(HibernateException ex)
		{
			session = sessionFactory.openSession();
		}
			
        try {
            String hql = "Select c from Cart c where c.idcart=:id";
            Query query = session.createQuery(hql);
            query.setParameter("id", id);
            c = (Cart)query.uniqueResult();
        } catch (HibernateException ex) {
            System.err.println(ex);
        } finally {
        	session.close();
        }
        return c;
	}
	
	private String createIdCart(String email, Date date)
    {
        String idCart;
        SimpleDateFormat sdf = new SimpleDateFormat("HHmmssddMMyyyy");
        String str = sdf.format(date);
        idCart = email.toUpperCase() + str;
        return idCart;
    }
	
	public boolean addCart(Cart cartCheckout, List<ProductCartDetail> lstProductCart)
	{
		Session session = null;
		try {
			session = sessionFactory.getCurrentSession();
		} catch (HibernateException ex) {
			session = sessionFactory.openSession();
		}

		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			
			cartCheckout.setIdcart(createIdCart(cartCheckout.getUserProfile().getEmail(), cartCheckout.getDate()));
			session.save(cartCheckout);
			
			for (ProductCartDetail pcd : lstProductCart) {
				CartDetail cd = new CartDetail();
				cd.setCart(cartCheckout);
				cd.setSku(pcd.productcart.getSku());
				cd.setNameProduct(pcd.productcart.getName());
				cd.setModel(pcd.productcart.getModel());
				cd.setPrice(pcd.productcart.getPrice());
				cd.setQuantity(pcd.quantity);
				if (pcd.productcart.getProductImages().iterator().hasNext())
					cd.setImageUrl( ((ProductImage)pcd.productcart.getProductImages().iterator().next()).getImageUrl());
				cartCheckout.getCartDetails().add(cd);
				session.save(cd);
			}
			transaction.commit();
		} catch (HibernateException ex) {
			transaction.rollback();
			System.err.println(ex);
			return false;
		} finally {
			session.close();
		}
		return true;
	}

	public List<Cart> getListCartByEmail(String email) {
		List<Cart> ds = null;
		
		Session session = null;
		try{
			session = sessionFactory.getCurrentSession();
		}
		catch(HibernateException ex)
		{
			session = sessionFactory.openSession();
		}
			
        try {
            String hql = "Select c from Cart c where c.userProfile.email=:email";
            Query query = session.createQuery(hql);
            query.setParameter("email", email);
            ds = query.list();
        } catch (HibernateException ex) {
            System.err.println(ex);
        } finally {
        	session.close();
        }
        return ds;
	}

	public List<Cart> getListCartByEmail(String email, int sortby) {
		List<Cart> ds = null;
		
		Session session = null;
		try{
			session = sessionFactory.getCurrentSession();
		}
		catch(HibernateException ex)
		{
			session = sessionFactory.openSession();
		}
			
        try {
            String hql = "Select c from Cart c where c.userProfile.email=:email ";
            
            switch (sortby)
            {
            case 1:
            	hql += " order by c.date desc ";
            	break;
            case 2:
            	hql += " order by c.totalPrice desc ";
            	break;
            case 3:
            	hql += " order by c.totalPrice asc ";
            	break;
            }
            
            Query query = session.createQuery(hql);
            query.setParameter("email", email);
            ds = query.list();
        } catch (HibernateException ex) {
            System.err.println(ex);
        } finally {
        	session.close();
        }
        return ds;
	}

	public boolean deleteCart(String idCart) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean deleteCartDetail(int idcartdetail) {
		
		CartDetail cd = getCartDetailByID(idcartdetail);
		if (cd == null)
			return false;
		
		Session session = null;
		try {
			session = sessionFactory.getCurrentSession();
		} catch (HibernateException ex) {
			session = sessionFactory.openSession();
		}

		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			
			
			session.delete(cd);
			transaction.commit();
		} catch (HibernateException ex) {
			transaction.rollback();
			System.err.println(ex);
			return false;
		} finally {
			session.close();
		}
		return true;
	}

	public CartDetail getCartDetailByID(int id) {
		CartDetail cd = null;
		
		Session session = null;
		try{
			session = sessionFactory.getCurrentSession();
		}
		catch(HibernateException ex)
		{
			session = sessionFactory.openSession();
		}
			
        try {
            String hql = "Select c from CartDetail c where c.id=:id";
            Query query = session.createQuery(hql);
            query.setParameter("id", id);
            cd = (CartDetail)query.uniqueResult();
        } catch (HibernateException ex) {
            System.err.println(ex);
        } finally {
        	session.close();
        }
        return cd;
	}

}
